<template>
  <div>
    <Breadcrumb :style="{ margin: '15px 0', float: 'left' }">
      <BreadcrumbItem>商品管理</BreadcrumbItem>
      <BreadcrumbItem>旅居商品</BreadcrumbItem>
    </Breadcrumb>
    <ButtonGroup :style="{ margin: '15px 0', float: 'right' }">
      <Button @click="CreateSku" type="warning">新增</Button>
      <Button v-if="superAdmin" @click="OnlineBatch" type="primary">批量上架</Button>
      <Button @click="OfflineBatch" type="primary">批量下架</Button>
      <Button @click="openExcelImport" type="info">商品导入</Button>
      <Button @click="openImageImport" type="info">图片导入</Button>
      <Button @click="exportExcel">导出</Button>
      <Button type="dashed"  @click="DeleteBatch">删除</Button>
    </ButtonGroup>
    <Content class="layer-content">
      <Form class="search" inline>
        <FormItem @submit.native.prevent>
          <Input style="width: 500px" v-model="keywords" search enter-button placeholder="请输入关键字" @on-search="searchGet"/>
        </FormItem>
        <FormItem>
					<Cascader placeholder="请选择分类" :data="category" v-model="categoryArray" :load-data="loadData"></Cascader>
				</FormItem>
        <FormItem v-if="superAdmin">
					<Select placeholder="请选择供应商" clearable @on-change="selectSupplier">
            <Option v-for="item in supplierArray" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
          </Select>
				</FormItem>
        <FormItem>
          <Select style="width: 100px" placeholder="有无图片" v-model="haveImage" clearable @on-change="imageFilter">
            <Option value="0" key="0">无图</Option>
            <Option value="1" key="1">有图</Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button @click="reset">重置</Button>
        </FormItem>
      </Form>
      <Tabs type="card" :animated="false" @on-click="switchTab">
        <TabPane name="-1" label="全部">
          <Table stripe :columns="columns8" :data="dataGridVo" @on-selection-change="Selector"></Table>
        </TabPane>
        <TabPane name="1" label="已上架">
          <Table stripe :columns="columns8" :data="dataGridVo" @on-selection-change="Selector"></Table>
        </TabPane>
        <TabPane name="0" label="未上架">
          <Table stripe :columns="columns8" :data="dataGridVo" @on-selection-change="Selector"></Table>
        </TabPane>
        <!-- <TabPane name="3" label="已售罄">
          <Table stripe :columns="columns8" :data="dataGridVo" @on-selection-change="Selector"></Table>
        </TabPane> -->
      </Tabs>
      <br />
      <HigPager v-model="query" :total="pageTotal" :init="Init"></HigPager>
      
      <Modal title="新增商品" :footer-hide="true" v-model="showCreate" fullscreen>
        <GoodsCreate :callbank="eventAction" :seletions="supplierArray" :key="createKey" ref="refSpcCreat"></GoodsCreate>
      </Modal>
      <Modal title="批量导入商品" :footer-hide="true" v-model="showImportExcel" width="600px">
        <ImportExcelVue :callbank="eventAction" :seletions="supplierArray" :key="createKey"></ImportExcelVue>
      </Modal>
      <Modal title="批量导出商品" :footer-hide="true" v-model="showExportExcel" width="600px">
        <ExportExcelVue :callbank="eventAction" :seletions="supplierArray" :key="createKey" ref="refExportExcel"></ExportExcelVue>
      </Modal>
      <Modal title="批量导入图片" :footer-hide="true" v-model="showUpload" width="800px">
        <UploadVue :callbank="eventAction" :key="createKey"></UploadVue>
      </Modal>
      <Modal title="编辑商品" :footer-hide="true" v-model="showUpdate" fullscreen>
        <GoodsUpdate :callbank="eventAction" :seletions="supplierArray" ref="refSpcUpdate"></GoodsUpdate>
      </Modal>
      <Modal title="发布商品" :footer-hide="true" v-model="showRelease">
        <ReleaseModule :callbank="eventAction" :seletions="onlineSeletor" ref="refReleaseModule"></ReleaseModule>
      </Modal>
    </Content>
  </div>
</template>
<script>
import GoodsCreate from "./create.vue"
import GoodsUpdate from "./update.vue"
import ReleaseModule from "./release.vue"
import UploadVue from "./upload.vue"
import ImportExcelVue from "./import-excel.vue"
import ExportExcelVue from "./export-excel.vue"
export default {
  data() {
    return {
      showRelease: false,
      showImportExcel: false,
      showExportExcel: false,
      showUpdate: false,
      showCreate: false,
      showUpload:false,
      keywords: null,
      createKey: 0,
      haveImage: null,
      onlineSeletor: [],
      superAdmin: this.$store.getUser('userType') === 9,
      uploadApi: `${env_config.upload_config.api}/agrobiz-file/v1.0/upload/single/file/binary`,
      uploadHeader: {
        Authorization: "Bearer " + this.$store.getToken(),
      },
      uploadParam: {
        catalog: "goods",
      },
      spuUploadListAd: [],
      spuFileViewAd: [],

      query: {
        equal: {
          goodsType: 10, //10旅居商品
          shopId: this.$store.getShop('shopId')
        },
        pageIndex: 1,
        pageSize: 15,
        // orderBy: {
        //   fields: ['sort_index'],
        //   asc: true
        // }
      },
      dialogVisible: false,
      goodsItem: {},
      columns8: [
        {
          title: "序号",
          key: "spuId",
          fixed: "left",
          width: 60,
          type: "selection",
        },
        {
          title: "商品图片",
          key: "skuImage",
          width: 100,
          render: (h, params) => {
            return h("div", [
              h("img",{
                  attrs: {src: params.row.skuImage},
                  style: {width: "50px",height: "46px"},
                },
              ),
            ])
          },
        },
        {
          title: "商品名称",
          key: "skuName",
          minWidth: 300,
          render: (h,params) => {
            return h('div',[
              h('a',{style:{color: '#515a6e'}},params.row.skuName + ' | ' + params.row.skuModel)
            ])
          }
        },
        {
          title: "预订模式",
          key: "bookingMode",
          minWidth: 180,
          render: (h,params) => {
            return h('div',[
              h('Tag',{props:{color: this.tagStyle(params.row.bookingMode)}},this.$dict.bookingMode.name(params.row.bookingMode))
            ])
          }
        },
        {
          title: "客房编号",
          key: "roomNumber",
          width: 150,
        },
        {
          title: "成本价",
          key: "systemPrice",
          width: 110,
          sortable: true,
          render: (h,params) => {
            return h('div',[
            h('a',{style:{fontSize: '12px',color: 'gray'}},'￥'),
              h('span',params.row.systemPrice?params.row.systemPrice.toFixed(2):'0.00'),
            ])
          }
        },
        {
          title: "零售价",
          key: "salesPrice",
          width: 110,
          sortable: true,
          render: (h,params) => {
            return h('div',[
            h('a',{style:{fontSize: '12px',color: 'gray'}},'￥'),
              h('span',params.row.salesPrice?params.row.salesPrice.toFixed(2):'0.00'),
            ])
          }
        },
        {
          title: "分销价",
          key: "wholesalePrice",
          width: 110,
          sortable: true,
          render: (h,params) => {
            return h('div',[
            h('a',{style:{fontSize: '12px',color: 'gray'}},'￥'),
              h('span',params.row.wholesalePrice?params.row.wholesalePrice.toFixed(2):'0.00'),
            ])
          }
        },
        {
          title: "佣金比例",
          key: "plfmProfitRatioText",
          sortable: true,
          width: 110,
        },
        {
          title: "分销佣金",
          key: "scmProfitRatioText",
          sortable: true,
          width: 110,
        },
        {
          title: "状态",
          key: "onlineStatus",
          width: 110,
          render: (h, params) => {
            return h("div", this.$enum.salesStatus(params.row.onlineStatus));
          },
        },
        {
          title: "单位",
          key: "skuUom",
          width: 80,
        },
        {
          title: "SKUID",
          key: "skuId",
          width: 190,
        },
        {
          title: "创建时间",
          key: "timeFormat",
          width: 110,
        },
        {
          title: "操作",
          key: "action",
          width: 120,
          fixed: "right",
          render: (h, params) => {
            return h("Dropdown",{props: {transfer:true,trigger:'click'}},
              [
                h("a",[h("a","下拉菜单"),h("Icon",{props: {type: "ios-arrow-down"}})]),
                h("DropdownMenu",{slot: "list"},
                  [
                    h("DropdownItem",{nativeOn:{click:()=>{this.EditView(params.row.skuId)}}},"编辑"),
                    h("DropdownItem",{nativeOn:{click:()=>{this.OnlineSku(params.row)}}},"上架"),
                    h("DropdownItem",{nativeOn:{click:()=>{this.OfflineSku(params.row)}},props:{disabled: params.row.onlineStatus !== 1}},"下架"),
                    h("DropdownItem",{nativeOn:{click:()=>{this.DeleteSku(params.row)}},props:{divided:true}},"删除")
                  ]
                ),
              ]
            )
          }
        }
      ],
      loading: true,
      categoryArray: [],
      supplierArray: [],
      dataGridVo: [],
      checkedArray: [],
      pageTotal: 0,
      onlineStatus: -1,
      spuGroupArray: [],
      category: []
    };
  },
  components: {
    GoodsCreate: GoodsCreate,
    GoodsUpdate: GoodsUpdate,
    ReleaseModule: ReleaseModule,
    UploadVue: UploadVue,
    ImportExcelVue: ImportExcelVue,
    ExportExcelVue: ExportExcelVue
  },
  watch: {
    categoryArray(val) {
			this.query.equal.categoryId = val[val.length - 1]
      this.query.pageIndex = 1
      this.Init()
		}
  },
  computed: {},
  methods: {
    //重置
    reset() {
      delete this.query.sqlLike
      delete this.query.equal.categoryId
      delete this.query.equal.skuImage
      delete this.query.queryNeqs
      this.keywords = null
      this.haveImage = null
      this.categoryArray = []
      this.query.pageIndex = 1
      this.Init()
    },
    //搜索
    searchGet() {
      let sqlLike = {
        fields: ['sku_name','ean_code','sku_id','org_name'],
        keyword: this.keywords
      }
      this.query.sqlLike = sqlLike
      this.query.pageIndex = 1
      this.Init()
    },
    
    tagStyle(status) {
      switch(status) {
        case 0:
          return 'default'
        case 1:
          return 'cyan'
        case 2:
          return 'green'
        default:
          return 'volcano'
      }
    },
    imageFilter(code) {
      if(code === '0') {
        delete this.query.queryNeqs
        this.query.equal.skuImage = 'https://view-assets.oss-cn-chengdu.aliyuncs.com/miniapp/sku_default.png'
      } else if(code === '1') {
        delete this.query.equal.skuImage
        this.query.queryNeqs = [{
          field: 'sku_image',
          value: 'https://view-assets.oss-cn-chengdu.aliyuncs.com/miniapp/sku_default.png'
        }]
      } else {
        delete this.query.equal.skuImage
        delete this.query.queryNeqs
      }
      this.Init()
    },
    switchTab(name) {
      this.onlineStatus = Number(name)
      this.query.pageIndex = 1
      this.Init()
      this.checkedArray = [];
    },
    Selector(selection) {
      this.onlineSeletor = selection
      this.checkedArray = []
      selection.forEach((element) => {
        this.checkedArray.push(element.skuId);
      });
    },
    selectSupplier(orgId) {
      this.query.equal.orgId = orgId
      this.Init()
    },
    //初始化商品
    Init() {
      delete this.query.equal.onlineStatus
      delete this.query.equal.inventory
      if(this.onlineStatus == 3) {
        this.query.equal.inventory = 0
      } else if(this.onlineStatus >= 0) {
        this.query.equal.onlineStatus = this.onlineStatus
      }

      new this.$rest({
        gateway: 'agroerp',
        service: "agroerp-shop",
        url: "/v1.0/view/basic/sku/page",
        query: this.query,
        action: (res) => {
          if (res.data.code === 20000) {
            const data = res.data.data
            data.list.forEach(element => {
              element.timeFormat = this.$date(element.postTime,'yyyy-MM-dd')
              // element.salesModelText = element.salesModel === 0 ? '自营' : '联营'
              if(element.plfmProfitRatio) {
                element.plfmProfitRatioText = element.plfmProfitRatio.mul(100) + '%'
              } else {
                element.plfmProfitRatioText = 0
              }
              if(element.scmProfitRatio) {
                element.scmProfitRatioText = element.scmProfitRatio.mul(100) + '%'
              } else {
                element.scmProfitRatioText = 0
              }
            })
            this.dataGridVo = data.list
            this.pageTotal = data.count
          } else {
            this.$Notice.warning({
              title: "商品获取失败",
              desc: `失败原因：${res.data.msg}`,
            });
          }
        },
      }).get();
    },
		getCategoryList(){
			new this.$rest({
				service: 'agroerp-shop',
				gateway: 'agroerp',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal:{
            categoryType: 0
          }  
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.category = data
					} else {
						this.$Notice.warning({
							title: '商品分类获取失败',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		getSupplierList(){
			new this.$rest({
        gateway: 'agrobiz',
				service: 'agrobiz-uc',
				url: '/v1.0/org/page',
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.supplierArray = data.list
					}
				}
			}).get()
		},
		loadData (item, callback) {
      item.loading = true;
      new this.$rest({
				service: 'agroerp-shop',
				 gateway: 'agroerp',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal: {
            categoryPid: item.value,
            categoryType: 0
          },
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						item.children = data
						item.loading = false;
            callback();
					} else {
						this.$Message.error(res.data.msg)
					}
				}
			}).get()
    },
    DeleteBatch() {
      if(this.checkedArray.length === 0) {
        return false
      }
      this.$Modal.confirm({
        title: '批量删除',
        content: `确定删除选择的${this.checkedArray.length}个商品吗？`,
        onOk: () => {
          new this.$rest({
            gateway: 'agroerp',
            service: "agroerp-mall",
            url: "/v1.0/plus/delete/goods/batch",
            data: {
              pojo: this.checkedArray,
            },
            action: (res) => {
              if (res.data.code === 20000) {
                this.$Message.success('删除成功')
                this.Init()
              } else {
                this.$Notice.error({
                  title: "删除失败",
                  desc: `失败原因：${res.data.msg}`,
                });
              }
            },
          }).delete()
        }
      })
    },
    //批量下架商品
    OfflineBatch() {
      if(this.checkedArray.length === 0) {
        return false
      }
      this.$Modal.confirm({
        title: '批量下架',
        content: `确定下架选择的${this.checkedArray.length}个商品吗？`,
        onOk: () => {
          new this.$rest({
            service: "agroerp-mall",
            gateway: 'agroerp',
            url: "/v1.0/plus/offline/goods/batch",
            data: {
              pojo: this.checkedArray,
            },
            action: (res) => {
              if (res.data.code === 20000) {
                this.$Message.success('下架成功')
                this.Init()
              } else {
                this.$Notice.error({
                  title: "下架失败",
                  desc: `失败原因：${res.data.msg}`,
                })
              }
            },
          }).put()
        }
      })
    },
    OnlineSku(item) {
      this.Selector([item])
      this.OnlineBatch()
    },
    OfflineSku(item) {
      if(item.onlineStatus !== 1) return false
      this.Selector([item])
      this.OfflineBatch()
    },
    DeleteSku(item) {
      this.Selector([item])
      this.DeleteBatch()
    },
    //批量上架商品
    OnlineBatch() {
      if(this.checkedArray.length === 0) {
        return false
      }
      this.showRelease = true
      this.$refs.refReleaseModule.Init(this.checkedArray[0])
    },
    openExcelImport() {
      this.showImportExcel = true
    },
    openImageImport() {
      this.showUpload = true
    },
    CreateSku() {
      this.showCreate = true
      this.$refs.refSpcCreat.Init()
    },
    EditView(skuId) {
      this.showUpdate = true
      this.$refs.refSpcUpdate.Init(skuId)
    },
    eventAction(){
      this.showUpdate = false
      this.showCreate = false
      this.showUpload = false
      this.showImportExcel = false
      this.showExportExcel = false
      this.showRelease = false
      this.createKey ++
      this.Init()
    },
    exportExcel() {
      this.showExportExcel = true
      this.$refs.refExportExcel.Init(this.supplierArray[0].orgId)
    }
  },
  mounted() {
    
  },
  created() {
    this.Init()
    this.getCategoryList()
    this.getSupplierList()
  },
};
</script>

<style lang="less" scoped>
</style>
